package com.ucode.application.controller.crm;

import java.util.ArrayList;
import java.util.List;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ucode.application.form.crm.BusinessStatusGroupForm;
import com.ucode.application.form.crm.BusinessStatusItem;
import com.ucode.application.security.CurrentLoginUserService;
import com.ucode.crm.mode.BusinessStatus;
import com.ucode.crm.mode.BusinessStatusGroup;
import com.ucode.crm.service.BusinessStatusGroupService;
import com.ucode.crm.vo.BusinessStatusGroupVo;
import com.ucode.sys.model.User;
import com.ucode.sys.service.UserService;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags="商机状态组")
@RestController
@RequestMapping("/cms-businessStatusGroup")
@Validated
public class BusinessStatusGroupController {
    
    @Autowired
    private CurrentLoginUserService currentLoginUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private BusinessStatusGroupService businessStatusGroupService;

    @PreAuthorize("hasAuthority('sys:dataRole:read') or hasRole('ADMIN')")
    @ApiOperation("根据条件分页查询列表")
    @GetMapping(value = "/list")
    public ResponseResult<Object> findPage(
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        
        Paginator<BusinessStatusGroup> page = businessStatusGroupService.queryPage(pageNum, pageSize);
        return ResponseResult.success(page);
    }
    
    @PreAuthorize("hasAuthority('sys:dataRole:read') or hasRole('ADMIN')")
    @ApiOperation(value="根据主键查询")
    @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "String",paramType = "path")
    @GetMapping("/getById/{id}")
    public ResponseResult<Object> getById(@PathVariable(name="id",required=true) Long id){
        
        BusinessStatusGroup businessStatusGroup = businessStatusGroupService.findById(id);
        if(businessStatusGroup == null || businessStatusGroup.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }
        
        BusinessStatusGroupVo businessStatusGroupVo = new BusinessStatusGroupVo();
        businessStatusGroupVo.setId(businessStatusGroup.getId());
        businessStatusGroupVo.setCreatedTime(businessStatusGroup.getCreatedTime());
        businessStatusGroupVo.setUpdatedTime(businessStatusGroup.getUpdatedTime());
        businessStatusGroupVo.setDeltag(businessStatusGroup.getDeltag());
        businessStatusGroupVo.setName(businessStatusGroup.getName());
        businessStatusGroupVo.setStatuz(businessStatusGroup.getStatuz());
        List<BusinessStatus> businessStatusItems = businessStatusGroupService.findBusinessStatuzs(businessStatusGroup.getId());
        businessStatusGroupVo.setItems(businessStatusItems);
        
        return ResponseResult.success(businessStatusGroupVo);
    }
    
    @ApiOperation(value="用户部门商机状态组列表")
    @GetMapping("/getOwnGroup")
    public ResponseResult<Object> getOwnGroup(){
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        User user = userService.findById(currentUserId);
        List<BusinessStatusGroup> businessStatusGroups = businessStatusGroupService.findDeptValidBusinessStatusGroup(user.getDeptId());
        return ResponseResult.success(businessStatusGroups);
    }
    
    @ApiOperation(value="商机状态列表")
    @GetMapping("/getGroupStatus/{groupId}")
    public ResponseResult<Object> getGroupStatus(@PathVariable(name="groupId",required=true) Long groupId){
        List<BusinessStatus> businessStatus = businessStatusGroupService.findBusinessStatuzs(groupId);
        return ResponseResult.success(businessStatus);
    }
    
    private BusinessStatusGroupVo formBuild(BusinessStatusGroupForm form,Long id){
        BusinessStatusGroupVo businessStatusGroupVo = new BusinessStatusGroupVo();
        businessStatusGroupVo.setId(id);
        businessStatusGroupVo.setName(form.getName());
        businessStatusGroupVo.setStatuz(form.getStatuz());
        
        List<BusinessStatusItem> items = form.getItems();
        List<BusinessStatus> businessStatusItems = new ArrayList<BusinessStatus>();
        int orderNum = 1;
        for(BusinessStatusItem item : items){
            BusinessStatus businessStatus = new BusinessStatus();
            businessStatus.setName(item.getName());
            businessStatus.setOrderNum(orderNum);
            businessStatus.setRate(item.getRate());
            businessStatusItems.add(businessStatus);
        }
        businessStatusGroupVo.setItems(businessStatusItems);
        return businessStatusGroupVo;
    }
    
    @PreAuthorize("hasAuthority('sys:dataRole:write') or hasRole('ADMIN')")
    @ApiOperation(value="创建")
    @PostMapping("/create")
    public ResponseResult<Object> create(@Validated @RequestBody BusinessStatusGroupForm form) {
        BusinessStatusGroupVo businessStatusGroupVo = formBuild(form, null);
        BusinessStatusGroup businessStatusGroup = businessStatusGroupService.insert(businessStatusGroupVo);
        return businessStatusGroup != null ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('sys:dataRole:write') or hasRole('ADMIN')")
    @ApiOperation(value="更新")
    @ApiImplicitParam(name = "id", value = "商机状态组ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/update/{id}")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
            @Validated @RequestBody BusinessStatusGroupForm form) {
        
        //判断是否有商机在使用
        BusinessStatusGroupVo businessStatusGroupVo = formBuild(form, id);
        businessStatusGroupService.update(businessStatusGroupVo);
        return ResponseResult.success();
        
    }
    
    @PreAuthorize("hasAuthority('sys:dataRole:write') or hasRole('ADMIN')")
    @ApiOperation(value="关联部门")
    @PostMapping("/relatedDept/{id}")
    public ResponseResult<Object> relatedDept(@PathVariable(name="id",required=true) Long id,
            @ApiParam(value ="部门(最多100条)") @Size(min=1,max = 100,message="一次最多选择100条") @RequestParam(value = "deptIds",required = true) List<Long> deptIds) {
        businessStatusGroupService.relatedDepts(id, deptIds);
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('sys:dataRole:write') or hasRole('ADMIN')")
    @ApiOperation(value="删除关联部门")
    @PostMapping("/deleteRelatedDept")
    public ResponseResult<Object> deleteRelatedDept(@ApiParam(value ="关联记录Id(最多100条)") @Size(min=1,max = 100,message="一次最多选择100条") @RequestParam(value = "relatedIds",required = true) List<Long> relatedIds) {
        businessStatusGroupService.deleteRelatedDepts(relatedIds);
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('sys:dataRole:write') or hasRole('ADMIN')")
    @ApiOperation(value="删除")
    @PostMapping("/delete")
    public ResponseResult<Object> delete(@ApiParam(value ="部门(最多100条)") @Size(min=1,max = 100,message="一次最多选择100条") @RequestParam(value = "deptIds",required = true) List<Long> ids) {
        for(Long id : ids){
          //校验是否有商机正在使用
          businessStatusGroupService.deleteByLogic(id);
        }
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('sys:dataRole:write') or hasRole('ADMIN')")
    @ApiOperation(value="更新商机状态")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "商机状态组ID", required = true, dataType = "String",paramType = "path"),
        @ApiImplicitParam(name = "statuz", value = "状态 :1启用 0禁用",allowableValues="1,0", required = true, dataType = "int", paramType = "path"),
    })
    @PostMapping("/updateStatuz/{id}/{statuz}")
    public ResponseResult<Object> updateStatuz(@PathVariable(name="id",required=true) Long id,@PathVariable(name="statuz",required=true) Integer statuz) {
        int i = businessStatusGroupService.updateStatuz(id, statuz);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
}
